package org.esgl3d.util;

public class HighPerformanceCounter {
	private long firstStart = 0;
	private long start = 0;
	private long lastElapsed = 0;
	private boolean isRunning = false;
	
	private long totalElapsed = 0;
	private long totalStops = 0;
	private final String name;
	
	public HighPerformanceCounter(String nameString) {
		name = nameString;
	}

	public void start() {
		start = System.nanoTime();
		if (firstStart == 0)
			firstStart = start;
		
		isRunning = true;
	}
	
	public void stop() {
		lastElapsed = System.nanoTime() - start;
		isRunning = false;
		
		totalStops += 1;
		totalElapsed += lastElapsed;
	}
	
	public void reset() {
		totalElapsed = 0;
		totalStops = 0;
		lastElapsed = 0;
		firstStart = 0;
		start = 0;
		isRunning = false;
	}
	
	public long getTotalStops() {
		return totalStops;
	}
	
	public long getCounterDurationMillis() {
		if (firstStart > 0) {
		 long duration = (System.nanoTime() - firstStart) / (1000*1000);
		 return duration;
		}
		return 0;
	}
	
	public long getAverageTotalElapsedMillis() {
		if (totalStops > 0) {
			return (totalElapsed / totalStops) / (1000*1000);
		}
		return 0;
	}
	
	public String getStatisticString() {
		return
			String.format("%s: Cnt: %d  Avg: %dms", name, getTotalStops(), getAverageTotalElapsedMillis());
	}
		
	public long getElapsedMillis() {
		long total = lastElapsed;
		if (isRunning)
			total += (System.nanoTime() - start);
				
		long diffInMillis = total / (1000*1000);
		return diffInMillis;
	}
}
